#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'
from . import local_data
from PySide import QtGui, QtCore
from .pyuic.skin_widget import Ui_skin_widget
from .painter.paintimage import get_size_image
from .baseui.noborderdialog import NoBorderDialog
from .title_bar_widget import TitleBarWidget
from .get_path import get_folder_path
from PIL import  Image
import colorsys
import os
import optparse

class ColorToolBrn(QtGui.QToolButton):
    def __init__(self, parent=None, color=[], size=16, icon=''):
        super(ColorToolBrn, self).__init__(parent)
        self.parent = parent
        self.setMinimumSize(QtCore.QSize(size, size))
        self.setMaximumSize(QtCore.QSize(size, size))
        self.setIconSize(QtCore.QSize(size, size))
        self._icon = icon
        self.color = color
        self._size = size
        #self.setAutoRaise(True)
        #self.setStyleSheet("background-color:rgb(%s,%s,%s)" % (color[0], color[1], color[2]))
        if self._icon:
            self.setIcon(QtGui.QIcon(self.scale_image()))
            self.color = self._get_main_color(self._icon)
        else:
            pix = get_size_image(QtGui.QColor(self.color[0], self.color[1], self.color[2]), (size, size))
            self.setIcon(QtGui.QIcon(pix))
        self.clicked.connect(self.on_clicked)
    def scale_images(self):
        thumb = QtGui.QPixmap(self._icon)
        pixmap_size = QtCore.QSize(self._size, self._size)
        result_pixmap = thumb.scaled(pixmap_size)#,QtCore.Qt.SmoothTransformation)#QtCore.Qt.KeepAspectRatio)
        return result_pixmap
    def on_clicked(self):
        print self._icon
        self.parent.skin_data['color'] = QtGui.QColor(self.color[0], self.color[1], self.color[2])
        self.parent.skin_data['image'] = self._icon
        self.parent.set_style()
        local_data.dump_skin_data({'color':self.color, 'image':self._icon})

    def _get_main_color(self, image):
        # 转换颜色模式，输入RGB值
        source_image = Image.open(image)
        # c_image = source_image.convert('RGBA')
        # # 生成缩略图，减少计算量
        # #image.thumbnail((200,200))
        # max_score = 0
        # main_color = None
        # for count, (r, g, b, a) in c_image.getcolors(c_image.size[0]*c_image.size[1]):
        #     if count < max_score:
        #         continue
        #     else:
        #         max_score = count
        #         main_color = (r, g, b, a)
        # return main_color
        return self.get_dominant_color(source_image)

    def scale_image(self):
        image = QtGui.QPixmap(self._icon)
        size = QtCore.QSize(self._size, self._size)

        result_image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32_Premultiplied)
        # mask_pixmap = QtGui.QPixmap(mask)

        painter = QtGui.QPainter(result_image)
        painter.drawPixmap(-25, 0, image)#.scaled(size))
        painter.end()
        result_pixmap = QtGui.QPixmap.fromImage(result_image)
        return result_pixmap

    def get_dominant_color(self, image):
        image = image.convert('RGBA')
        image.thumbnail((200,200))
        max_score = None
        dominant_color = None
        for count, (r, g, b, a) in image.getcolors(image.size[0]*image.size[1]):
            # 跳过纯黑色
            if a == 0:
                continue
            saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1]
            y = min(abs(r*2014 + g*4130 + b*802 + 4096 + 131072) >> 13, 235)
            y = (y-16.0) / (235-16)

            # 忽略高亮色
            if y > 0.8 or y < 0.2:
                continue

            score = (saturation + 0.1) * count
            if score > max_score:
                max_score = score
                dominant_color = (r, g, b)
        return dominant_color


class SkinWidget(NoBorderDialog):
    def __init__(self, parent=None):
        super(SkinWidget, self).__init__(parent)
        self.parent = parent
        self._ui = Ui_skin_widget()
        self._ui.setupUi(self)
        #self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint)#QtCore.Qt.Drawer| QtCore.Qt.WindowCloseButtonHint)#FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint) #setWindowFlags(Qt::Drawer);
        #self._ui.toolButton.
        self.title_bar = TitleBarWidget(self)
        self.title_bar._ui.skin_btn.setVisible(0)
        self.setContentsMargins(5, 5, 5, 5)
        self._ui.title_layout.addWidget(self.title_bar)
        self.add_color_btn()
        self.add_image_btn()
    def add_color_btn(self):
        default_color = [(0, 155, 216), (40, 138, 221),
              (49, 166, 107), (218, 67, 78),
              (229, 98, 129), (177, 99, 159),
              (107, 81, 192), (89, 92, 160),
              (48, 116, 193), (0, 130, 154),
              (21, 156, 119), (79, 176, 172),
              (122, 197, 196), (155, 183, 214),
              (128, 77, 77), (240, 188, 89),
              (207, 186, 170), (0, 0, 0)]
        for i, color in enumerate(default_color):
            btn = ColorToolBrn(self.parent, color, 40)
            self._ui.color_layout.addWidget(btn, 0, i, 1, 1)

    def add_image_btn(self):
        skin_path = get_folder_path('skin')
        for i in range(18):
            icon_path = os.path.join(skin_path, '%s.png' % str(i))
            # icon_path = 'D:/develop/apps/tder/desktop/src/desktop/skin/%s.png' % str(i)
            btn = ColorToolBrn(parent=self.parent, size=122, icon=icon_path.replace('\\', '/'))
            self._ui.image_layout.addWidget(btn, i/6, i%6, 1, 1)


if __name__ == '__main__':
    app = QtGui.QApplication([])
    SW = SkinWidget()
    SW.show()
    app.exec_()